package android.component;


import android.life.viewmodel.HasDefaultViewModelProviderFactory;
import android.life.viewmodel.ViewModelProvider;
import android.life.viewmodel.ViewModelStore;
import android.life.viewmodel.ViewModelStoreOwner;
import android.log.Log;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.Lifecycle;
import ohos.aafwk.ability.LifecycleStateObserver;

/**
 * 模拟Android的Activity，具有ViewModelStore,否则无法使用ViewModel的相关功能
 * 新的Android的库里的Fragment和Activity都是具有ViewModelStore的功能
 */
public class CompatAbility extends Ability implements
        ViewModelStoreOwner, HasDefaultViewModelProviderFactory {
    /**
     * true if the activity is being destroyed in order to recreate it with a new configuration
     */
    boolean mChangingConfigurations = false;
    private ViewModelStore mViewModelStore;
    private ViewModelProvider.Factory mDefaultFactory;

    public CompatAbility() {
        super();
        getLifecycle().addObserver((LifecycleStateObserver) (event, intent) -> {
            Log.d("ViewModelAbility life event:"+ event);
            if (event == Lifecycle.Event.ON_STOP) {
                if (!isChangingConfigurations()) {
                    Log.d("ViewModelAbility clearViewModelStore in Ability");
                    getmViewModelStore().clear();
                }
            }
        });
    }

    @Override
    public ViewModelStore getmViewModelStore() {
        if (getAbilityPackage() == null) {
            throw new RuntimeException("you Ability do not attach an AbilityPackage");
        }
        ensureViewModelStore();
        return mViewModelStore;

    }

    void ensureViewModelStore() {
        if (mViewModelStore == null) {
            mViewModelStore = new ViewModelStore();
        }
    }

    @Override
    public ViewModelProvider.Factory getDefaultViewModelProviderFactory() {
        if (getAbilityPackage() == null) {
            throw new IllegalStateException("Your activity is not yet attached to the "
                    + "Application instance. You can't request ViewModel before onCreate call.");
        }
        if (mDefaultFactory == null) {
            mDefaultFactory = ViewModelProvider.NewInstanceFactory.getInstance();
        }
        return mDefaultFactory;
    }

    public boolean isChangingConfigurations() {
        return mChangingConfigurations;
    }
}
